package com.bestv.search.management.datasyn;

import com.bestv.search.common.cache.SystemCache;
import com.bestv.search.common.model.History;
import com.bestv.search.common.model.SearchKeywordWrapper;
import com.bestv.search.management.command.HistoryCommand;
import com.bestv.search.management.command.HitCommand;
import com.bestv.search.management.xfire.ISearchWS;
import org.apache.log4j.Logger;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author Michael Wang
 */

// $Id: HitSync.java 88 2012-05-08 09:06:52Z wbwang $
public class HitSync extends QuartzJobBean {

    static boolean isRunning = false;
    Logger logger = Logger.getLogger(HitSync.class);
    private HitCommand hitCommand;
    private HistoryCommand historyCommand;
    private SystemCache systemCache;

    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        if (!isRunning) {
            isRunning = true;
            run();
        } else {
            logger.error("Last hit sync process is still running");
        }
    }

    void run() {
        logger.info("Start hit and history sync @" + new Date());

        ISearchWS service;
        Service serviceModel = new ObjectServiceFactory().create(ISearchWS.class);
        String url = systemCache.getWebServiceEngineUrls().get(systemCache.getLocalDataSourceKey());
        String[] soapUrls = StringUtils.tokenizeToStringArray(url, SystemCache.WEB_SERVICE_EURL_DELIMITERS);
        if (soapUrls == null || soapUrls.length == 0) {
            logger.error("Gets info failed, no web service interface found from site "
                    + systemCache.getLocalDataSourceKey());
        }

        try {
            for (int i = 0; i < soapUrls.length; i++) {
                try {
                    String soapUrl = soapUrls[i];
                    logger.debug("Get infomation from " + soapUrl);

                    service = (ISearchWS) new XFireProxyFactory().create(serviceModel, soapUrl);
                    service.hitLock();
                    List<SearchKeywordWrapper> wrapperList = service.hitKeywordSync();
                    logger.debug("Get " + wrapperList.size() + " keyword wrappers.");
                    service.clearEngineKeyword();
                    service.hitFree();
                    hitCommand.saveSearchKeywordList(wrapperList, systemCache.getLocalDataSourceKey());

                    service.historyLock();
                    List<History> historyList = service.historySync();
                    logger.debug("Get " + historyList.size() + " users' histories.");
                    service.clearEngineHistory();
                    service.historyFree();
                    historyCommand.saveHistories(historyList, systemCache.getLocalDataSourceKey());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            isRunning = false;
        }

        logger.info("End hit and history sync @" + new Date());
        isRunning = false;
    }

    public HitCommand getHitCommand() {
        return hitCommand;
    }

    public void setHitCommand(HitCommand hitCommand) {
        this.hitCommand = hitCommand;
    }

    public HistoryCommand getHistoryCommand() {
        return historyCommand;
    }

    public void setHistoryCommand(HistoryCommand historyCommand) {
        this.historyCommand = historyCommand;
    }

    public SystemCache getSystemCache() {
        return systemCache;
    }

    public void setSystemCache(SystemCache systemCache) {
        this.systemCache = systemCache;
    }
}
